#!/usr/bin/env python
# -*- conding: utf-8 -*-

"""
@Time     : 2024/10/25 6:25
@Author   : liujingmao
@File     : 1.基础LangGraph示例.py
"""

from typing import TypedDict, Annotated, Any

import dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages

dotenv.load_dotenv()

llm = ChatOpenAI(model="gpt-4o-mini")


# 1.创建状态图，并使用GraphState作为状态数据
class State(TypedDict):
    """图结构的状态数据"""
    messages: Annotated[list, add_messages]
    use_name: str


def chatbot(state: State, config: dict) -> Any:
    """聊天机器人节点，使用大语言模型根据传递的消息列表生成内容"""
    ai_message = llm.invoke(state["messages"])
    return {"messages": [ai_message], "use_name": "chatbot"}


graph_builder = StateGraph(State)

# 2.添加节点
graph_builder.add_node("llm", chatbot)

# 3.添加边
graph_builder.add_edge(START, "llm")
graph_builder.add_edge("llm", END)

# 4.编译图为Runnable可运行组件
graph = graph_builder.compile()

# 5.调用图架构应用
print(graph.invoke(
    {"messages": [("human", "你好，你是谁，我叫慕小课，我想知道刀郎最近的演唱会在哪里举行")], "use_name": "graph"}))

"""
E:\code\llmops\llmops-api\venv\Scripts\python.exe E:\code\llmops\llmops-api\study\65-LangGraph介绍与基础组件上手\1.基础LangGraph示例.py 
{'messages': [HumanMessage(content='你好，你是谁，我叫慕小课，我想知道刀郎最近的演唱会在哪里举行', additional_kwargs={}, response_metadata={}, id='c20b2c60-1266-41e7-8548-b2c5fc9db663'), AIMessage(content='你好，慕小课！很高兴认识你。打篮球和游泳都是很棒的运动，可以锻炼身体、放松心情。你打篮球有多久了？或者你最喜欢哪种泳姿呢？', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 51, 'prompt_tokens': 22, 'total_tokens': 73, 'completion_tokens_details': {'reasoning_tokens': 0}, 'prompt_tokens_details': {'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_f59a81427f', 'finish_reason': 'stop', 'logprobs': None}, id='run-3db2e4d3-f86c-4861-b5b1-ec53bd449d4f-0', usage_metadata={'input_tokens': 22, 'output_tokens': 51, 'total_tokens': 73, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 0}})], 'use_name': 'chatbot'}

"""
